import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import '../models/unified_config.dart';
import '../services/config_service.dart';
import '../config_import_export.dart';

class UnifiedProjectPage extends StatefulWidget {
  final bool isDarkMode;

  const UnifiedProjectPage({super.key, required this.isDarkMode});

  @override
  State<UnifiedProjectPage> createState() => _UnifiedProjectPageState();
}

class _UnifiedProjectPageState extends State<UnifiedProjectPage> {
  UnifiedConfig _config = UnifiedConfig();
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;

  // TextEditingController for dynamic updates
  late TextEditingController _projectPathController;
  late TextEditingController _outputDirController;
  late TextEditingController _customDependenciesController;

  // 常用Python模块列表
  final Map<String, bool> _commonModules = {
    'requests': false,
    'numpy': false,
    'pandas': false,
    'matplotlib': false,
    'pillow': false,
    'opencv-python': false,
    'tensorflow': false,
    'torch': false,
    'flask': false,
    'django': false,
    'fastapi': false,
    'sqlalchemy': false,
    'psycopg2': false,
    'pymongo': false,
    'redis': false,
    'celery': false,
    'beautifulsoup4': false,
    'scrapy': false,
    'selenium': false,
    'pytest': false,
    'click': false,
    'pydantic': false,
    'aiohttp': false,
    'asyncio': false,
  };

  @override
  void initState() {
    super.initState();
    _projectPathController = TextEditingController();
    _outputDirController = TextEditingController();
    _customDependenciesController = TextEditingController();
    print('DEBUG: UnifiedProjectPage initState called');
    _loadConfig();
  }

  @override
  void dispose() {
    _projectPathController.dispose();
    _outputDirController.dispose();
    _customDependenciesController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print(
      'DEBUG: UnifiedProjectPage didChangeDependencies called, reloading config',
    );
    _loadConfig();
  }

  Future<void> _loadConfig() async {
    print('DEBUG: _loadConfig() called');
    try {
      final configService = await ConfigService.getInstance();
      final config = await configService.loadUnifiedConfig();
      print('DEBUG: Loaded config - projectPath: ${config.projectPath}');
      print('DEBUG: Loaded config - outputDir: ${config.outputDir}');
      print('DEBUG: Loaded config - buildMode: ${config.buildMode}');

      setState(() {
        _config = config;
        // 更新TextEditingController
        _projectPathController.text = config.projectPath ?? '';
        _outputDirController.text = config.outputDir ?? '';
        _customDependenciesController.text = config.customDependencies.join(
          ', ',
        );

        // 更新常用模块选择状态
        for (String module in _commonModules.keys) {
          _commonModules[module] = config.customDependencies.contains(module);
        }
      });
      print('DEBUG: setState completed with new config');
    } catch (e) {
      print('DEBUG: Error loading config: $e');
    }
  }

  Future<void> _saveConfig() async {
    print('DEBUG: _saveConfig() called');
    print('DEBUG: Saving config - projectPath: ${_config.projectPath}');
    print('DEBUG: Saving config - outputDir: ${_config.outputDir}');
    print('DEBUG: Saving config - buildMode: ${_config.buildMode}');

    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      try {
        final configService = await ConfigService.getInstance();
        await configService.saveUnifiedConfig(_config);
        print('DEBUG: Config saved successfully');
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('配置已保存')));
        }
      } catch (e) {
        print('DEBUG: Error saving config: $e');
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
        }
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  Future<void> _importConfig() async {
    try {
      final success = await ConfigImportExportService.importConfig(context);
      if (success && mounted) {
        // 重新加载配置
        await _loadConfig();
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('配置导入成功')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('导入失败: $e')));
      }
    }
  }

  Future<void> _exportConfig() async {
    try {
      final success = await ConfigImportExportService.exportConfig(context);
      if (success && mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('配置导出成功')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('导出失败: $e')));
      }
    }
  }

  Future<void> _selectPythonFile() async {
    print('DEBUG: _selectPythonFile() called');
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['py'],
    );

    if (result != null) {
      final filePath = result.files.single.path!;
      print('DEBUG: Selected Python file: $filePath');

      setState(() {
        _config.projectPath = filePath;
        _projectPathController.text = filePath;

        // 自动设置输出目录为文件所在目录
        final directory = filePath.substring(0, filePath.lastIndexOf('\\'));
        _config.outputDir = directory;
        _outputDirController.text = directory;
      });

      await _saveConfig();
    }
  }

  Future<void> _selectOutputDir() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

    if (selectedDirectory != null) {
      setState(() {
        _config.outputDir = selectedDirectory;
        _outputDirController.text = selectedDirectory;
      });
      await _saveConfig();
    }
  }

  void _updateCommonModules() {
    // 获取选中的常用模块
    List<String> selectedModules = _commonModules.entries
        .where((entry) => entry.value)
        .map((entry) => entry.key)
        .toList();

    // 获取自定义依赖（排除已选择的常用模块）
    List<String> customDeps = _customDependenciesController.text
        .split(',')
        .map((e) => e.trim())
        .where((e) => e.isNotEmpty && !_commonModules.containsKey(e))
        .toList();

    // 合并所有依赖
    List<String> allDependencies = [...selectedModules, ...customDeps];
    String allDepsString = allDependencies.join(', ');

    // 更新输入框显示和配置
    setState(() {
      _config.customDependencies = allDependencies;
      _customDependenciesController.text = allDepsString;
    });

    _saveConfig();
  }

  Widget _buildCommonModulesGrid() {
    return Wrap(
      spacing: 8.0,
      runSpacing: 8.0,
      children: _commonModules.entries.map((entry) {
        return SizedBox(
          width: 200,
          child: Card(
            elevation: 1,
            child: CheckboxListTile(
              title: Text(
                entry.key,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
                overflow: TextOverflow.ellipsis,
              ),
              subtitle: Text(
                _getModuleDescription(entry.key),
                style: const TextStyle(fontSize: 12),
                overflow: TextOverflow.ellipsis,
              ),
              value: entry.value,
              onChanged: (bool? value) {
                setState(() {
                  _commonModules[entry.key] = value ?? false;
                });
                _updateCommonModules();
              },
              dense: true,
              contentPadding: const EdgeInsets.symmetric(horizontal: 8),
            ),
          ),
        );
      }).toList(),
    );
  }

  String _getModuleDescription(String module) {
    switch (module) {
      case 'requests':
        return 'HTTP库';
      case 'numpy':
        return '数值计算';
      case 'pandas':
        return '数据分析';
      case 'matplotlib':
        return '数据可视化';
      case 'pillow':
        return '图像处理';
      case 'opencv-python':
        return '计算机视觉';
      case 'tensorflow':
        return '机器学习';
      case 'torch':
        return 'PyTorch深度学习';
      case 'flask':
        return 'Web框架';
      case 'django':
        return 'Web框架';
      case 'fastapi':
        return '现代Web API';
      case 'sqlalchemy':
        return 'ORM数据库';
      case 'psycopg2':
        return 'PostgreSQL驱动';
      case 'pymongo':
        return 'MongoDB驱动';
      case 'redis':
        return 'Redis客户端';
      case 'celery':
        return '任务队列';
      case 'beautifulsoup4':
        return 'HTML解析';
      case 'scrapy':
        return '网络爬虫';
      case 'selenium':
        return '浏览器自动化';
      case 'pytest':
        return '测试框架';
      case 'click':
        return '命令行工具';
      case 'pydantic':
        return '数据验证';
      case 'aiohttp':
        return '异步HTTP';
      case 'asyncio':
        return '异步编程';
      default:
        return '常用模块';
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('项目配置'),
        backgroundColor: theme.colorScheme.surface,
        foregroundColor: theme.colorScheme.onSurface,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Form(
              key: _formKey,
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 基本设置
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Icon(Icons.settings, color: Colors.blue),
                                const SizedBox(width: 8),
                                Text(
                                  '基本设置',
                                  style: theme.textTheme.titleMedium,
                                ),
                              ],
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _projectPathController,
                              decoration: InputDecoration(
                                labelText: 'Python文件路径',
                                hintText: '选择要编译的Python文件',
                                border: const OutlineInputBorder(),
                                suffixIcon: IconButton(
                                  icon: const Icon(Icons.folder_open),
                                  onPressed: _selectPythonFile,
                                ),
                              ),
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请选择Python文件';
                                }
                                return null;
                              },
                              onChanged: (value) {
                                _config.projectPath = value;
                                _saveConfig();
                              },
                            ),
                            const SizedBox(height: 16),
                            TextFormField(
                              controller: _outputDirController,
                              decoration: InputDecoration(
                                labelText: '输出目录',
                                hintText: '选择输出目录',
                                border: const OutlineInputBorder(),
                                suffixIcon: IconButton(
                                  icon: const Icon(Icons.folder_open),
                                  onPressed: _selectOutputDir,
                                ),
                              ),
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请选择输出目录';
                                }
                                return null;
                              },
                              onChanged: (value) {
                                _config.outputDir = value;
                                _saveConfig();
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 构建模式
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Icon(Icons.build, color: Colors.green),
                                const SizedBox(width: 8),
                                Text(
                                  '构建模式',
                                  style: theme.textTheme.titleMedium,
                                ),
                              ],
                            ),
                            const SizedBox(height: 16),
                            RadioListTile<BuildMode>(
                              title: const Text('独立模式 (Standalone)'),
                              subtitle: const Text('生成包含所有依赖的目录'),
                              value: BuildMode.standalone,
                              groupValue: _config.buildMode,
                              onChanged: (BuildMode? value) {
                                setState(() {
                                  _config.buildMode = value!;
                                });
                                _saveConfig();
                              },
                            ),
                            RadioListTile<BuildMode>(
                              title: const Text('单文件模式 (Onefile)'),
                              subtitle: const Text('生成单个可执行文件'),
                              value: BuildMode.onefile,
                              groupValue: _config.buildMode,
                              onChanged: (BuildMode? value) {
                                setState(() {
                                  _config.buildMode = value!;
                                });
                                _saveConfig();
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 依赖管理
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Icon(Icons.extension, color: Colors.orange),
                                const SizedBox(width: 8),
                                Text(
                                  '依赖管理',
                                  style: theme.textTheme.titleMedium,
                                ),
                              ],
                            ),
                            const SizedBox(height: 16),

                            // 常用模块多选列表
                            Row(
                              children: [
                                Icon(
                                  Icons.library_books,
                                  color: Colors.blue,
                                  size: 20,
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  '常用Python模块 (${_commonModules.length}个)',
                                  style: theme.textTheme.titleSmall?.copyWith(
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),
                            Container(
                              height: 250,
                              decoration: BoxDecoration(
                                border: Border.all(
                                  color: Colors.blue.shade300,
                                  width: 2,
                                ),
                                borderRadius: BorderRadius.circular(12),
                                color: theme.colorScheme.surface,
                              ),
                              child: _commonModules.isEmpty
                                  ? const Center(child: Text('没有可用的模块'))
                                  : SingleChildScrollView(
                                      padding: const EdgeInsets.all(12),
                                      child: _buildCommonModulesGrid(),
                                    ),
                            ),
                            const SizedBox(height: 16),

                            // 自定义依赖输入
                            Text('自定义依赖', style: theme.textTheme.titleSmall),
                            const SizedBox(height: 8),
                            TextFormField(
                              controller: _customDependenciesController,
                              decoration: const InputDecoration(
                                labelText: '自定义依赖 (用逗号分隔)',
                                hintText: '例如: requests,numpy,pandas',
                                border: OutlineInputBorder(),
                              ),
                              maxLines: 3,
                              onChanged: (value) {
                                _updateCommonModules();
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),

                    // 优化设置
                    Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Icon(Icons.speed, color: Colors.purple),
                                const SizedBox(width: 8),
                                Text(
                                  '优化设置',
                                  style: theme.textTheme.titleMedium,
                                ),
                              ],
                            ),
                            const SizedBox(height: 16),
                            SwitchListTile(
                              title: const Text('启用LTO优化'),
                              subtitle: const Text('链接时优化，提高性能但增加编译时间'),
                              value: _config.enableLto,
                              onChanged: (bool value) {
                                setState(() {
                                  _config.enableLto = value;
                                });
                                _saveConfig();
                              },
                            ),
                            SwitchListTile(
                              title: const Text('禁用控制台'),
                              subtitle: const Text('隐藏控制台窗口（仅Windows）'),
                              value: _config.disableConsole,
                              onChanged: (bool value) {
                                setState(() {
                                  _config.disableConsole = value;
                                });
                                _saveConfig();
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 32),

                    // 配置操作按钮
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isLoading ? null : _importConfig,
                            icon: const Icon(Icons.file_upload),
                            label: const Text('导入配置'),
                            style: ElevatedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(vertical: 16),
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _isLoading ? null : _exportConfig,
                            icon: const Icon(Icons.file_download),
                            label: const Text('导出配置'),
                            style: ElevatedButton.styleFrom(
                              padding: const EdgeInsets.symmetric(vertical: 16),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),

                    // 配置会自动保存
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.green.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(
                          color: Colors.green.withOpacity(0.3),
                        ),
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.check_circle,
                            color: Colors.green,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            '配置已自动保存',
                            style: TextStyle(
                              color: Colors.green.shade700,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}
